package cn.teduymdj.jxc.service.impl;

import cn.teduymdj.jxc.ex.ServiceException;
import cn.teduymdj.jxc.mapper.GoodsMapper;
import cn.teduymdj.jxc.mapper.ReturnListGoodsMapper;
import cn.teduymdj.jxc.mapper.ReturnListMapper;
import cn.teduymdj.jxc.pojo.dto.*;
import cn.teduymdj.jxc.pojo.entity.CustomerReturnList;
import cn.teduymdj.jxc.pojo.entity.ReturnList;
import cn.teduymdj.jxc.pojo.entity.ReturnListGoods;
import cn.teduymdj.jxc.pojo.vo.*;
import cn.teduymdj.jxc.security.LoginPrincipal;
import cn.teduymdj.jxc.service.ReturnListGoodsService;
import cn.teduymdj.jxc.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;

import static cn.teduymdj.jxc.service.impl.CustomerReturnListGoodsServiceImpl.PAID_STATE;

/**
 * 处理退货商品实体表相关业务的实现类
 *
 * @author 陈坤鹏
 */
@Slf4j
@Service
public class ReturnListGoodsServiceImpl implements ReturnListGoodsService {

    @Autowired
    ReturnListMapper returnListMapper;
    @Autowired
    ReturnListGoodsMapper returnListGoodsMapper;
    @Autowired
    GoodsMapper goodsMapper;

    public ReturnListGoodsServiceImpl() {
        log.debug("创建业务对象:ReturnListGoodsServiceImpl");
    }

    @Override
    public void save(ReturnListAddNewDTO02 returnList) {
        if (returnList.getReturnNumber()==null) {
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, "保存失败,必须有单号");
        }
        int saleNumber = returnListMapper.countBySaleNumber(returnList.getReturnNumber());
        if (saleNumber != 0) {
            // 是:添加失败，抛出异常，单号已存在
            String message = "保存退货单失败，单号已存在!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        ReturnListAddNewDTO returnListAddNewDTO = new ReturnListAddNewDTO();
        BeanUtils.copyProperties(returnList, returnListAddNewDTO);
        returnListAddNewDTO.setUserId(getLoginInfo().getId());
        int result = returnListMapper.addNew(returnListAddNewDTO);
        // 判断是否添加成功
        if (result != 1) {
            String message = "添加失败，服务器忙，请稍后重试";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        List<ReturnListGoodsAddNewDTO> goodsList = returnList.getTableData();
        if (goodsList == null) {
            String message = "保存退货单据失败，退货单必须包含商品！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_BAD_REQUEST, message);
        }

        int rows = returnListGoodsMapper.addNewBatch(goodsList);
        if (rows < 1) {
            throw new ServiceException(ServiceCode.ERR_INSERT, "添加失败，服务器忙，请稍后重试");
        }
        //修改货物表中的库存和状态
        for (ReturnListGoodsAddNewDTO goods : goodsList) {
            goodsMapper.updateInventoryQuantityAndStateById(goods.getGoodsId(), goods.getNum(), 2);
        }


    }

    @Override
    public List<ReturnListListItemVO> getReturnlist(SelectReturnListCondition selectReturnListCondition) {
        return returnListMapper.listByCondition(selectReturnListCondition);
    }

    @Override
    public List<ReturnListGoodsListItemVO> getReturnListGoodsByReturnListId(Long returnListId) {
        return returnListGoodsMapper.listByListId(returnListId);
    }

    @Override
    public void delete(Long returnListId) {
        ReturnListStandardVO queryResult = returnListMapper.getStandardById(returnListId);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：此id对应的数据不存在，则抛出异常(ERR_NOT_FOUND)
            String message = "删除退货单失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        int rows = returnListMapper.deleteById(returnListId);
        if (rows != 1) {
            String message = "删除退货单失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        rows = returnListGoodsMapper.deleteByListId(returnListId);
        if (rows < 1) {
            String message = "删除退货单商品失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public ReturnList getReturnList(Long returnListId) {
        return null;
    }

    @Override
    public void updateState(Integer state, Long id) {

    }

    @Override
    public List<ReturnListGoods> getReturnListGoodsByReturnListId(Long returnListId, Long goodsTypeId, String codeOrName) {
        return null;
    }

    @Override
    public void setPaid(Long id) {
        updateEnableById(id, 1);
    }

    @Override
    public void setUnpaid(Long id) {
        updateEnableById(id, 2);
    }

    @Override
    public List<PurchaseListCountListItemVO> getReturnListGoodsByCondition(SelectReturnCondition selectReturnCondition) {
        List<PurchaseListCountListItemVO> list = returnListGoodsMapper.listByCondition(selectReturnCondition);
        list.forEach(g->g.setType("退货"));
        return list;
    }

    private void updateEnableById(Long id, int isPaid) {
        ReturnListStandardVO queryResult = returnListMapper.getStandardById(id);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：此id对应的数据不存在，则抛出异常(ERR_NOT_FOUND)
            String message = "修改支付状态失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断状态是否冲突（当前已经是目标状态）
        if (queryResult.getState().equals(isPaid)) {
            String message = "修改支付失败，退货单已经处于该状态！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        ReturnListUpdateInfoDTO returnList = new ReturnListUpdateInfoDTO();
        returnList.setId(id);
        returnList.setState(isPaid);
        int rows = returnListMapper.update(returnList);
        if (rows != 1) {
            String message = "修改支付失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    private LoginPrincipal getLoginInfo() {
        return (LoginPrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }
}
